package com.example.score.controllrt;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.score.common.AjaxResult;
import com.example.score.entity.*;
import com.example.score.entity.vo.GradeVo;
import com.example.score.entity.vo.TUserVo;
import com.example.score.service.ClassService;
import com.example.score.service.GradeService;
import com.example.score.service.UserService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/scores")
public class GradeController {
    @Autowired
    private ClassService classService;
    @Autowired
    private GradeService gradeService;

    @Autowired
    private UserService userService;
    /**
     * 导出本班答辩汇总成绩
     *
     * @param request
     * @param response //     * @param fileName
     * @throws IOException
     */

    @GetMapping("/exportData")
    public void exportData(Integer classId,HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {

            String gradeDetaiFilename = classService.getClassNameByID(classId);
            this.setExcelResponseProp(response, gradeDetaiFilename);
            List<TotalGradeDetail> list = gradeService.getTotalGrade(classId);
            System.out.println(list);
            ExcelWriter writer = ExcelUtil.getWriter();
            writer.write(list, true);
            ServletOutputStream outputStream = response.getOutputStream();
            writer.flush(outputStream, true);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 导出本班答辩成绩明细
     *
     * @param request
     * @param response
     * @throws IOException
     */


    @GetMapping("/exportDataDetails")
    public void exportDataDetails(Integer classId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            String gradeDetaiFilename = classService.getClassNameByID(classId);
            this.setExcelResponseProp(response, gradeDetaiFilename);
            List<TotalGradeDetail> list = gradeService.getAllGradeDetails(classId);
            ExcelWriter writer = ExcelUtil.getWriter();
            writer.write(list, true);
            ServletOutputStream outputStream = response.getOutputStream();
            writer.flush(outputStream, true);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据答辩人ID获取未评分的人
     * @param id
     * @return
     */
    @RequestMapping("/unargument")
    public AjaxResult unargument(Integer id) {
        if (id == null || id <= 0) {
            return AjaxResult.fail(-1, "参数错误");
        }
        List<TUser> argument = gradeService.unargument(id);
        if (argument != null && argument.size() >= 0) {
            return AjaxResult.success(argument);
        }
        return AjaxResult.fail(-2, "获取失败");
    }

    /**
     * 根据答辩人ID获取已经评分的人
     * @param id
     * @return
     */
    @RequestMapping("/argument")
    public AjaxResult argument(Integer id) {
        if (id == null || id <= 0) {
            return AjaxResult.fail(-1, "参数错误");
        }
        List<GradeVo> argument = gradeService.argument(id);
        if (argument != null && argument.size() >= 0) {
            return AjaxResult.success(argument);
        }
        return AjaxResult.fail(-2, "获取失败");
    }

    @RequestMapping("/viewed")
    public AjaxResult viewed(Integer userId, Integer classId) {
        if (userId == null || userId <= 0 || classId == null || classId <= 0) {
            return AjaxResult.fail(-1, "参数错误");
        }
        Map<String, Integer> map = new HashMap<>();
        map.put("userId", userId);
        map.put("classId", classId);
        List<GradeStudentList> viewed = gradeService.viewed(map);
        if (viewed != null || viewed.size() > 0) {
            return AjaxResult.success(viewed);
        }
        return AjaxResult.fail(-2, "获取已评分列表失败");
    }

    //评价打分，grade中的pfr为dbr打分。返回1表示正确评价
    @RequestMapping("/updateGrade")
    public AjaxResult judgeAnswerGrade(HttpServletRequest request,
                                       HttpServletResponse response,
                                       @RequestParam Integer pfr,
                                       @RequestParam Integer dbr,
                                       @RequestParam Integer classId,
                                       @RequestParam Integer pf1,
                                       @RequestParam Integer pf2,
                                       @RequestParam Integer pf3,
                                       @RequestParam Integer pf4,
                                       @RequestParam Integer pf5,
                                       @RequestParam Integer zf,
                                       @RequestParam String memo) throws IOException {
        //通过username获取当前答辩学生信息
        //通过username获取当前登录用户信息
//        TUser loginUser =  (TUser) request.getSession().getAttribute("user");
//        System.out.println(loginUser);
            //生成答辩人为answerUser评分人为loginUser的修改记录需要Grade记录信息
            Grade grade = new Grade();
            grade.setDbr(dbr);
            grade.setPfr(pfr);
            grade.setClass_id(classId);
            grade.setPf1(pf1);
            grade.setPf2(pf2);
            grade.setPf3(pf3);
            grade.setPf4(pf4);
            grade.setPf5(pf5);
            grade.setZf(zf);
            grade.setMemo(memo);
            if (gradeService.updateAnswerGrade(grade) > 0) {
                return AjaxResult.success("评分成功");
            }
        return AjaxResult.fail(-2, "评分失败");
    }

    @RequestMapping("/update")
    public AjaxResult update(@RequestBody UpdateScore updateScore) {
        System.out.println(updateScore);
        if (updateScore == null) {
            return AjaxResult.fail(-1, "参数错误");
        }
        if (gradeService.updateScore(updateScore) > 0) {
            return AjaxResult.success("评分成功");
        }
        return AjaxResult.fail(-2, "评分 失败");
    }

    @RequestMapping("/pfbzmsg")
    public AjaxResult pfbzsmg(Integer classId) {
        if (classId == null || classId <= 0) {
            return AjaxResult.fail(-1, "参数错误");
        }
        List<Course> pfbzmsg = gradeService.pfbzmsg(classId);
        if (pfbzmsg != null) {
            return AjaxResult.success(pfbzmsg);
        }
        return AjaxResult.fail(-2, "获取课程描述失败");
    }
    @RequestMapping("/showAll")
    public AjaxResult showAll(Integer classId) {
        if (classId == null || classId <= 0) {
            return AjaxResult.fail(-1, "参数错误");
        }
        List<TotalGradeDetail> list = gradeService.showAll(classId);
        List<List<String>> groupedPfs = new ArrayList<>();

        for (TotalGradeDetail student : list) {
            List<String> pfGroup = new ArrayList<>();
            pfGroup.add(student.getDbrUsernam());
            pfGroup.add(student.getDbrChname());
            if(student.getPfbzs() == 1){
                pfGroup.add(String.valueOf(student.getPf1()));
            }
            if(student.getPfbzs() == 2){
                pfGroup.add(String.valueOf(student.getPf1()));
                pfGroup.add(String.valueOf(student.getPf2()));
            }
            if(student.getPfbzs() == 3){
                pfGroup.add(String.valueOf(student.getPf1()));
                pfGroup.add(String.valueOf(student.getPf2()));
                pfGroup.add(String.valueOf(student.getPf3()));
            }
            if(student.getPfbzs() == 4){
                pfGroup.add(String.valueOf(student.getPf1()));
                pfGroup.add(String.valueOf(student.getPf2()));
                pfGroup.add(String.valueOf(student.getPf3()));
                pfGroup.add(String.valueOf(student.getPf4()));
            }
            if(student.getPfbzs() == 5){
                pfGroup.add(String.valueOf(student.getPf1()));
                pfGroup.add(String.valueOf(student.getPf2()));
                pfGroup.add(String.valueOf(student.getPf3()));
                pfGroup.add(String.valueOf(student.getPf4()));
                pfGroup.add(String.valueOf(student.getPf5()));
            }
            pfGroup.add(String.valueOf(student.getZf()));
            groupedPfs.add(pfGroup);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        map.put("pfbzes", groupedPfs);
        if (list != null) {
            return AjaxResult.success(map);
        }
        return AjaxResult.fail(-2, "获取学生列表失败");
    }

    @RequestMapping("/Lottery")
    public AjaxResult Lottery(Integer classId,HttpServletRequest request, HttpServletResponse response) throws IOException{
        if (classId == null || classId <= 0) {
            return AjaxResult.fail(-1, "参数错误");
        }
        RandomStudent RandomStudent = gradeService.getRandomStudent(classId);
        System.out.println(666);
        System.out.println(RandomStudent);

        if (RandomStudent != null){
            return AjaxResult.success(RandomStudent);
        }
        if (RandomStudent == null){
            return AjaxResult.fail(-3,"无剩余未答辩学生");
        }
        return AjaxResult.fail(-2, "生成随机学生失败");
    }

    @RequestMapping("talking")
    public AjaxResult talking(Integer classId) throws IOException{
        if (classId == null || classId <= 0) {
            return AjaxResult.fail(-1, "参数错误");
        }
        RandomStudent Talking = gradeService.talking(classId);
        if (Talking == null){
            return AjaxResult.success("无答辩学生");
        }
        if (Talking != null){
            return AjaxResult.success(Talking);
        }
        return AjaxResult.fail(-2, "查询失败");
    }

    @RequestMapping("endTalkingStudent")
    public AjaxResult endTalkingStudent(Integer classId)throws IOException{
        if (classId == null || classId <= 0) {
            return AjaxResult.fail(-1, "参数错误");
        }
        gradeService.endTalkingStudent(classId);
        return AjaxResult.success("结束当前学生答辩！");
    }

    @RequestMapping("over")
    public AjaxResult over (Integer classId) throws IOException{
        if (classId == null || classId <= 0) {
            return AjaxResult.fail(-1, "参数错误");
        }
        gradeService.over(classId);
        return AjaxResult.success("答辩结束！");
    }



    /**
     * 设置响应结果
     *
     * @param response    响应结果对象
     * @param rawFileName 文件名
     * @throws UnsupportedEncodingException 不支持编码异常
     */

    
    private void setExcelResponseProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xls");
    }
}
